package com.xingongchang.baolebei.activity;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.external.androidquery.callback.AjaxStatus;
import com.external.maxwin.view.XListView;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechError;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.MyViewGroup;
import com.insthub.BeeFramework.view.ToastView;
import com.umeng.analytics.MobclickAgent;
import com.xingongchang.baolebei.BaolebeiManager;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.adapter.CategoryAdapter;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.SearchModel;
import com.xingongchang.baolebei.protocol.CATEGORY;
import com.xingongchang.baolebei.protocol.FILTER;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class SearchActivity02 extends Activity  implements BusinessResponse,OnClickListener{
	private ImageView search;
	private EditText input;

	private SearchModel searchModel;

	private Button btn[];
	private MyViewGroup layout;

	private XListView parentListView;

	CategoryAdapter parentListAdapter;
	   @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_category);
		input = (EditText)findViewById(R.id.search_input);
		search = (ImageView)findViewById(R.id.top_view_search);
		layout = (MyViewGroup)findViewById(R.id.search_layout);
//		search_back = (ImageView) view.findViewById(R.id.search_back);
		parentListView = (XListView)findViewById(R.id.parent_list);
//		search_back.setOnClickListener(this);
		search.setOnClickListener(this);

		input.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					try {
						Intent intent = new Intent(SearchActivity02.this,
								ProductListActivity.class);
						FILTER filter = new FILTER();
						filter.keywords = input.getText().toString().toString();
						intent.putExtra(ProductListActivity.FILTER, filter
								.toJson().toString());
						startActivity(intent);
						SearchActivity02.this.overridePendingTransition(
								R.anim.push_right_in, R.anim.push_right_out);

					} catch (JSONException e) {

					}
				}
				return false;
			}
		});

		if (null == searchModel) {
			searchModel = new SearchModel(SearchActivity02.this);
			searchModel.searchCategory();
		}

		searchModel.addResponseListener(this);

		parentListAdapter = new CategoryAdapter(SearchActivity02.this,
				searchModel.categoryArrayList);
		parentListView.setAdapter(parentListAdapter);
		parentListView.setPullLoadEnable(false);
		parentListView.setPullRefreshEnable(false);
		parentListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {

						if (position - 1 < searchModel.categoryArrayList.size()) {
							CATEGORY category = searchModel.categoryArrayList
									.get(position - 1);
							try {
								if (category.children.size() > 0) {
									Intent it = new Intent(SearchActivity02.this,
											CategoryActivity.class);
									it.putExtra("category", category.toJson()
											.toString());
									it.putExtra("category_name",
											searchModel.categoryArrayList
													.get(position - 1).name);
									startActivity(it);
									SearchActivity02.this.overridePendingTransition(
											R.anim.push_right_in,
											R.anim.push_right_out);
								} else {
									Intent intent = new Intent(SearchActivity02.this,
											ProductListActivity.class);
									FILTER filter = new FILTER();
									filter.category_id = String
											.valueOf(category.id);
									intent.putExtra(ProductListActivity.FILTER,
											filter.toJson().toString());
									startActivity(intent);
									SearchActivity02.this.overridePendingTransition(
											R.anim.push_right_in,
											R.anim.push_right_out);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}

					}
				});

		addKeywords();
	}
	// 动态添加button，并设置监听
		public void addKeywords() {

			if (searchModel.list.size() > 0) {

				layout.removeAllViews();
				btn = new Button[searchModel.list.size()];
				for (int i = 0; i < searchModel.list.size(); i++) {
					View view = LayoutInflater.from(SearchActivity02.this).inflate(
							R.layout.button_view, null);
					btn[i] = (Button) view.findViewById(R.id.search_keyword);
					btn[i].setText(searchModel.list.get(i).toString());
					layout.addView(view);
				}

				for (int k = 0; k < searchModel.list.size(); k++) {
					btn[k].setTag(k);
					btn[k].setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {

							int a = (Integer) v.getTag();
							try {
								Intent intent = new Intent(SearchActivity02.this,
										ProductListActivity.class);
								FILTER filter = new FILTER();
								filter.keywords = btn[a].getText().toString();
								intent.putExtra(ProductListActivity.FILTER, filter
										.toJson().toString());
								startActivity(intent);
								SearchActivity02.this
										.overridePendingTransition(
												R.anim.push_right_in,
												R.anim.push_right_out);
							} catch (JSONException e) {

							}

						}
					});
				}
			}

		}
		public void showRecognizerDialog() {

			RecognizerDialog recognizerDialog = new RecognizerDialog(SearchActivity02.this, "appid="
					+ BaolebeiManager.getXunFeiCode());

			recognizerDialog.setEngine("sms", null, null);
			recognizerDialog.setListener(new RecognizerDialogListener() {
				@Override
				public void onResults(ArrayList<RecognizerResult> results,
						boolean arg1) {
					StringBuffer result = new StringBuffer();
					for (RecognizerResult r : results) {
						result.append(r.text);
					}
					if (result.length() > 0) {
						input.setText(result.toString().substring(0,
								result.toString().length() - 1));
					}

				}

				@Override
				public void onEnd(SpeechError arg0) {
					if (input.getText().toString().equals("")) {

						// Toast.makeText(getActivity(), you_not_speak, 0).show();
						ToastView toast = new ToastView(SearchActivity02.this,
								getString(R.string.you_did_not_speak));
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					} else {
						try {
							Intent intent = new Intent(SearchActivity02.this,
									ProductListActivity.class);
							FILTER filter = new FILTER();
							filter.keywords = input.getText().toString();
							intent.putExtra(ProductListActivity.FILTER, filter
									.toJson().toString());
							startActivity(intent);
							SearchActivity02.this.overridePendingTransition(
									R.anim.push_right_in, R.anim.push_right_out);
						} catch (JSONException e) {

						}
					}

				}
			});
			recognizerDialog.show();

		}

		public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status) {
			if (url.endsWith(ProtocolConst.SEARCHKEYWORDS)) {
				addKeywords();
			} else if (url.endsWith(ProtocolConst.CATEGORY)) {
				parentListAdapter.notifyDataSetChanged();
			}
		}

		@Override
		public void onDestroy() {
			super.onDestroy();
		}

		@Override
		public void onResume() {
			super.onResume();
			MobclickAgent.onPageStart("Search");
		}

		@Override
		public void onPause() {
			super.onPause();
			MobclickAgent.onPageEnd("Search");
		}
		@Override
		public void onClick(View v) {
			
		}
}
